<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\api\controller\send;
use think\Request;
use think\Db;

/**
 * 全部变量token
 */

//1、GET（SELECT）：从服务器取出资源（一项或多项）
//2、POST（CREATE）：在服务器新建一个资源
//3、PUT（UPDATE）：在服务器更新资源（客户端提供完整资源数据）
//4、PATCH（UPDATE）：在服务器更新资源（客户端提供需要修改的资源数据）
//5、DELETE（DELETE）：从服务器删除资源

class River extends Api
{
    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['*'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    /**
     * 测试appid，正式请数据库进行相关验证
     * 测试appkey，正式请数据库进行相关验证
     */
    public static $appid = 'das';
    public static $appkey = '43211234';

    // http://mg.acciot.com.tw/api/river/test
    // http://localhost:9100//api/river/test?md5=
    public function test()
    {
        $dd1 =
            [
                's1' => '11',
                's2' => '22'
            ];
        $dd = [];
        if(sizeof($dd)>0)
            echo '0--sizeof($dd)>0...';
        else
            echo '0--sizeof($dd)===0...';
        $dd = $dd1;

        if(empty($dd))
            echo '1--empty($dd)...';
        else
            echo '1--!!!!empty($dd)...';
        $dd = [];
        if(empty($dd))
            echo '2--empty($dd)...';
        else
            echo '2--!!!!empty($dd)...';
        return;
        $md5 = $this->request->request('md5');
        $data = [];
        $jsonInfo = \app\admin\model\river\Json::where('md5', $md5)->find();
        if($jsonInfo)
        {
            $data = json_decode($jsonInfo['json'], true);
        }
        echo sizeof($data[0]['goodsInfo']);
        return;
    }

    private function isTokenExperiod($token)
    {
        // 根据tokenbefore
        $tokenbackupitem = \app\admin\model\river\Tokenbackup::where('token', $token)->find();
        if(!$tokenbackupitem)
        {
            return -1;
        }
        else
        {
            // 判断是否过期
            if( ($tokenbackupitem['create_time'] + $tokenbackupitem['periodOfValidity']*3600) <= time() )
            {
                // 已经过期了
                return -2;
            }
        }

        return 0;
    }

    /*
     * 获取token
     * 請求：GET http://mg.acciot.com.tw/api/river/token?username=henry&appid=das&appkey=43211234
     *      GET http://localhost:9100/api/river/token?username=henry&appid=das&appkey=43211234
     */
    public function token()
    {
        $username = $this->request->request('username');
        if(!$username)
        {
            $this->error("Parameter name is error", null, -98);
        }
        $appid = $this->request->request('appid');
        if(!$appid)
        {
            $this->error("Parameter name is error", null, -98);
        }
        $appkey = $this->request->request('appkey');
        if(!$appkey)
        {
            $this->error("Parameter name is error", null, -98);
        }

        $method = $this->request->method();
        if ($method == 'GET') {
            $data = [
                'appid' => $appid,
                'appkey' => $appkey,
                'username' => $username
            ];

            //按照键名对关联数组进行升序排序
            ksort($data);

            $MakeTokenRowMaterial = urldecode(strtolower(http_build_query($data)));

            // 根据tokenbefore
            $tokenbackupitem = \app\admin\model\river\Tokenbackup::where('tokenBefore', $MakeTokenRowMaterial)->find();
            if(!$tokenbackupitem)
            {
                // 没有，要插入到数据库表中
                //连接上时间戳
                $tokenbefore = $MakeTokenRowMaterial . time();
                //計算md5
                $tokenNew = md5($tokenbefore);
                self::writeTokenBackup($MakeTokenRowMaterial, $tokenNew);

                // 返回查询的结果
                $data = [
                    'token' => $tokenNew
                ];

                $this->success("success", $data, 0);
            }
            else
            {
                // 判断是否过期
                if( ($tokenbackupitem['create_time'] + $tokenbackupitem['periodOfValidity']*3600) <= time() )
                {
                    // 已经过期了,要重新生成
                    //连接上时间戳
                    $tokenbefore = $MakeTokenRowMaterial . time();
                    //計算md5
                    $tokenNew = md5($tokenbefore);
                    // 更新
                    $tokenbackupitem['token'] = $tokenNew;
                    // 更新这个token的create_time，用当前时间
                    $tokenbackupitem['create_time'] = time();
                    // 写入数据
                    $tokenbackupitem->save();

                    // 返回查询的结果
                    $data = [
                        'token' => $tokenNew
                    ];

                    $this->success("success", $data, 0);
                }
                // 返回查询的结果
                $data = [
                    'token' => $tokenbackupitem['token']
                ];

                $this->success("success", $data, 0);
            }
        } else if ($method == 'POST') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'PUT') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'DELETE') {
            $this->error('請求方式錯誤',null,-99);
        }
        $this->error('請求方式錯誤',null,-99);
    }

    /*
     * 提供查詢美果商城平臺的商品詳情
     * 請求參數: 商品 ID 或 -1(所有商品)
     * 回傳:  多結果，商品 ID、商品名稱、來源商家 ID、來源商家名稱等
     */
    // GET http://mg.acciot.com.tw/api/river/GoodDetailInfo?goodsId=xxx&token=adfada
    // GET http://localhost:9100/api/river/GoodDetailInfo?goodsId=203&token=770048f341e10d8275eb7ab61ab6e523
    public function goodDetailInfo()
    {
        // 判断token正确否？
        $token = $this->request->request('token');
        if(!$token)
        {
            $this->error("error token", null, -2);
        }

        $ret = self::isTokenExperiod($token);
        if($ret == -1)  // 不存在，token值错误
        {
            $this->error("error token", null, -2);
        }
        else if($ret == -2) // token过期
        {
            $this->error("token is experiod", null, -19);
        }

        $method = $this->request->method();
        if ($method == 'GET') {
            $id = $this->request->request('goodsId');
            if(!$id)
            {
                $this->error("Parameter name is error", null, -98);
            }
            else
            {
                $sql = "SELECT id,pcate,ccate,title,thumb,unit,productprice,marketprice,total,sales,subtitle,merchid,keywords FROM ims_ewei_shop_goods";
                $sql .= " WHERE id = {$id}";
            }
            $category_list = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                ->query($sql);
            //echo json_encode($category_list);

            // 组合数据
            $dataArray = [];
            foreach ($category_list as $item) {
                $data = [
                    'goodsId' => -1,
                    'pcate' => -1,
                    'ccate' => -1,
                    'goodsName' => "",
                    'thumb' => "",
                    'unit' => "",
                    'productPrice' => -1.0,
                    'marketPrice' => -1.0,
                    'total' => -1,
                    'sales' => -1,
                    'subGoodsName' => "",
                    'merchId' => -1,
                    'keywords' => ""
                ];

                $data['goodsId'] = $item['id'];
                $data['pcate'] = $item['pcate'];
                $data['ccate'] = $item['ccate'];
                $data['goodsName'] = $item['title'];
                $thumb = $item['thumb'];
                if(substr($thumb,0,5) != "http:")
                {
                    $thumb = 'https://image.localmuzi.com/' . $thumb;
                }
                $data['thumb'] = $thumb;
                $data['unit'] = $item['unit'];
                $data['productPrice'] = $item['productprice'];
                $data['marketPrice'] = $item['marketprice'];
                $data['total'] = $item['total'];
                $data['sales'] = $item['sales'];
                $data['subGoodsName'] = $item['subtitle'];
                $data['merchId'] = $item['merchid'];
                $data['keywords'] = $item['keywords'];
                $dataArray[] = $data;
            }
            $this->success('success', $dataArray, 0);
        } else if ($method == 'POST') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'PUT') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'DELETE') {
            $this->error('請求方式錯誤',null,-99);
        }

        $this->error('請求方式錯誤',null,-99);
    }

    /* 包含新旧版本
     * 提供查詢美果商城平臺的商品詳情
     * 請求參數: 商品 ID 或 -1(所有商品)
     * 回傳:  多結果，商品 ID、商品名稱、來源商家 ID、來源商家名稱等
     */
    // GET http://mg.acciot.com.tw/api/river/goodsSearch?goodsName=漁曜海物&keywords=香蕉&merchId=106&token=adfada
    // GET http://localhost:9100/api/river/goodsSearch?goodsName=漁曜海物&keywords=香蕉&merchId=106&token=8ecf712a080c69b262b4b0e7e9d6c26f
    public function goodsSearch()
    {
        // 判断token正确否？
        $token = $this->request->request('token');
        if(!$token)
        {
            $this->error("error token", null, -2);
        }
        $ret = self::isTokenExperiod($token);
        if($ret == -1)  // 不存在，token值错误
        {
            $this->error("error token", null, -2);
        }
        else if($ret == -2) // token过期
        {
            $this->error("token is experiod", null, -19);
        }

        $method = $this->request->method();
        if ($method == 'GET') {
            $title = $this->request->request('goodsName');
            if(!$title)
                $title = $this->request->request('title');  // 旧版本
            $keywords = $this->request->request('keywords');    // 新旧一样
            $merchid = $this->request->request('merchId');

            if(!$merchid)
                $merchid = $this->request->request('merchid');  // 旧版本

            if(!$title and !$keywords and !$merchid)
            {
                $this->error("Name,keywords and merchid cannot all be NULL", null, -20);
            }

            $sql = "SELECT id,pcate,ccate,title,thumb,unit,productprice,marketprice,total,sales,subtitle,merchid,keywords FROM ims_ewei_shop_goods WHERE";
            if($title)
            {
                $sql .= " title like '%{$title}%'";
            }
            // if($keywords)
            // {
            //     if(substr_compare($sql, "WHERE", -strlen("WHERE")) == 0)
            //         $sql .= " keywords like '%{$keywords}%'";
            //     else
            //         $sql .= " OR keywords like '%{$keywords}%'";
            // }
            if($merchid)
            {
                if(substr_compare($sql, "WHERE", -strlen("WHERE")) == 0)
                    $sql .= " merchid = {$merchid}";
                else
                    $sql .= " AND merchid = {$merchid}";
            }
            $category_list = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                ->query($sql);

            // 组合数据
            $dataArray = [];
            foreach ($category_list as $item) {
                $data = [
                    'goodsId' => -1,
                    'id' => -1,  // 旧版本
                    'pcate' => -1,
                    'ccate' => -1,
                    'goodsName' => "",
                    'title' => "",  // 旧版本
                    'thumb' => "",
                    'unit' => "",
                    'productPrice' => -1.0,
                    'productprice' => -1.0,  // 旧版本
                    'marketPrice' => -1.0,
                    'marketprice' => -1.0,  // 旧版本
                    'total' => -1,
                    'sales' => -1,
                    'subGoodsName' => "",
                    'subtitle' => "",  // 旧版本
                    'merchId' => -1,
                    'merchid' => -1,  // 旧版本
                    'keywords' => ""
                ];
                $data['goodsId'] = $item['id'];
                $data['id'] = $item['id'];  // 旧版本
                $data['pcate'] = $item['pcate'];
                $data['ccate'] = $item['ccate'];
                $data['goodsName'] = $item['title'];
                $data['title'] = $item['title'];  // 旧版本
                $thumb = $item['thumb'];
                if(substr($thumb,0,5) != "http:")
                {
                    $thumb = 'https://image.localmuzi.com/' . $thumb;
                }
                $data['thumb'] = $thumb;
                $data['unit'] = $item['unit'];
                $data['productPrice'] = $item['productprice'];
                $data['productprice'] = $item['productprice'];  // 旧版本
                $data['marketPrice'] = $item['marketprice'];
                $data['marketprice'] = $item['marketprice'];  // 旧版本
                $data['total'] = $item['total'];
                $data['sales'] = $item['sales'];
                $data['subGoodsName'] = $item['subtitle'];
                $data['subtitle'] = $item['subtitle'];  // 旧版本
                $data['merchId'] = $item['merchid'];
                $data['merchid'] = $item['merchid'];  // 旧版本
                $data['keywords'] = $item['keywords'];
                $dataArray[] = $data;
            }
            $this->success('success', $dataArray, 0);
        } else if ($method == 'POST') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'PUT') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'DELETE') {
            $this->error('請求方式錯誤',null,-99);
        }

        $this->error('請求方式錯誤',null,-99);
    }

    /*
     * 提供查詢美果商城訂單
     * 1、Mobile、nickname、goodsid可以為空
     * 2、一筆訂單至少有一個商品；如果是用戶同時購買多個商品，會有多筆訂單，這時有個主訂單isparent: 0，
     * 如果isparent是數字，該數字就是主訂單的ID，主訂單的商品信息都會是空的，商品信息都分布在子訂單中；
     * 如果是同一訂單同一商戶有多個商品就會合一個訂單中
    */
    // GET http://mg.acciot.com.tw/api/river/getOrders?startTime=2020/07/28&endTime=2020/08/01&platformId=LINE_Ua2b67a5b7ac9d3923a9ec04cc6dc7250&nickname=xxx&goodsid=0&token=xxx
    // GET http://localhost:9100/api/river/getOrders?startTime=2020/07/28&endTime=2020/08/01&platformId=LINE_Ua2b67a5b7ac9d3923a9ec04cc6dc7250&nickname=xxx&goodsid=0&token=b82b180733be534213e461a0cefbc704
    public function getOrders()
    {
        // 判断token正确否？
        $token = $this->request->request('token');
        if(!$token)
        {
            $this->error("error token", null, -2);
        }
        $ret = self::isTokenExperiod($token);
        if($ret == -1)  // 不存在，token值错误
        {
            $this->error("error token", null, -2);
        }
        else if($ret == -2) // token过期
        {
            $this->error("token is experiod", null, -19);
        }
        $method = $this->request->method();
        if ($method == 'GET') {
            $starttime = $this->request->request('startTime',null);
            // 日期转换为时间戳
            $starttime = strtotime($starttime . "00:00:00");
            $endtime = $this->request->request('endTime',null);
            // 日期转换为时间戳
            $endtime = strtotime($endtime . "24:00:00");

            // 平臺類型:FB, LINE, WEIXIN,先不用
            $comefrom = $this->request->request('platformType',""); // 对应ims_ewei_shop_member里的comefrom
            $channelId = $this->request->request('channelId',"");   // 对应ims_ewei_shop_member里的channelId
            $openid = $this->request->request('platformId');
            if(!empty($openid))
            {
                if(!empty($channelId))
                {
                    // 先串接channelId-lineId=xxxxx-yyyyyyyyy
                    // xxxxx為channelID
                    // yyyyy為paltfromID
                    $openid = $openid . '-' . $channelId;
                }
                else if(strtoupper($comefrom) == 'LINE')
                {
                    // 判断有没有前缀
                    if(substr($openid,0,5) != "LINE_")
                    {
                        $openid = "LINE_" . $openid;
                        //echo 'LINE_' . $openid;
                    }
                }
                $nickname = '';
            }
            else
            {
                // 有lineid，就不查nickname
                $nickname = $this->request->request('nickName',"");
            }
            $mobile = $this->request->request('mobile',"");
            $goodsid = $this->request->request('goodsId',"");
            $shippingType = $this->request->request('shippingType',"");
            if(!empty($shippingType))
            {
                if($shippingType == 'DELIVERING')
                    $shippingType = 1;
                else
                    $shippingType = 2;
            }

            // 查詢開始日期 和 查詢結束日期 都要有
            if(!$starttime or !$endtime)
            {
                $this->error("Parameter name is error", null, -98);
            }

            // 通用的格式
            $sql = "SELECT b.`id` as mid, b.`realname`, b.`mobile`, b.`nickname`, b.`comefrom`, b.`channelId`,";
            $sql .=" c.`goodsid`, c.`price`, c.`total`,";
            $sql .=" a.`id` as orderid, a.`ordersn`, a.`isparent`, a.`parentid`,";
            $sql .=" a.`price` as totalprice, a.`goodsprice`, a.`discountprice`, a.`dispatchprice`, a.`status`, a.`createtime`,d.`title`";
            $sql .=" FROM ims_ewei_shop_order a INNER JOIN ims_ewei_shop_member b ON a.`openid` = b.`openid`";
            $sql .=" INNER JOIN ims_ewei_shop_order_goods c ON  a.`id` = c.`orderid`";
            $sql .=" INNER JOIN ims_ewei_shop_goods d ON c.`goodsid` = d.`id`";
            $sql .=" WHERE a.`createtime` >= {$starttime} AND a.`createtime` <= {$endtime}";
            $sql .=" AND a.`isparent` != 1 AND a.`parentid` = 0 AND a.`status` >= 0";

            // 只取ims_ewei_shop_order表里，满足条件，且isparent=1的
            $sqlIsparent = "SELECT b.`id` as mid, b.`realname`, b.`mobile`, b.`nickname`, b.`comefrom`, b.`channelId`,";
            $sqlIsparent .=" a.`id` as orderid, a.`ordersn`, a.`isparent`, a.`parentid`,";
            $sqlIsparent .=" a.`price` as totalprice, a.`goodsprice`, a.`discountprice`, a.`dispatchprice`, a.`status`, a.`createtime`";
            $sqlIsparent .=" FROM ims_ewei_shop_order a INNER JOIN ims_ewei_shop_member b ON a.`openid` = b.`openid`";
            $sqlIsparent .=" WHERE a.`createtime` >= {$starttime} AND a.`createtime` <= {$endtime}";
            $sqlIsparent .=" AND a.`isparent` = 1 AND a.`status` >= 0";

            // 只取parentid=orderid记录
            $sqlSon = "SELECT b.`id` as mid, b.`realname`, b.`mobile`, b.`nickname`, b.`comefrom`, b.`channelId`,";
            $sqlSon .=" c.`goodsid`, c.`price`, c.`total`,";
            $sqlSon .=" a.`id` as orderid, a.`ordersn`, a.`isparent`, a.`parentid`,";
            $sqlSon .=" a.`price` as totalprice, a.`goodsprice`, a.`discountprice`, a.`dispatchprice`, a.`status`, a.`createtime`,d.`title`";
            $sqlSon .=" FROM ims_ewei_shop_order a INNER JOIN ims_ewei_shop_member b ON a.`openid` = b.`openid`";
            $sqlSon .=" INNER JOIN ims_ewei_shop_order_goods c ON  a.`id` = c.`orderid`";
            $sqlSon .=" INNER JOIN ims_ewei_shop_goods d ON c.`goodsid` = d.`id`";
            $sqlSon .=" WHERE a.`createtime` >= {$starttime} AND a.`createtime` <= {$endtime} AND a.`status` >= 0";

            if(!empty($openid))
            {
                //echo '10.....';
                $sql .=" AND a.`openid` = '{$openid}'";
                $sqlIsparent .=" AND a.`openid` = '{$openid}'";
                $sqlSon .=" AND a.`openid` = '{$openid}'";
            }
            if(!empty($comefrom))
            {
                //echo '11.....';
                $sql .=" AND b.`comefrom` = '{$comefrom}'";
                $sqlIsparent .=" AND b.`comefrom` = '{$comefrom}'";
                $sqlSon .=" AND b.`comefrom` = '{$comefrom}'";
            }
            if(!empty($channelId))
            {
                //echo '12.....';
                $sql .=" AND b.`channelId` = '{$channelId}'";
                $sqlIsparent .=" AND b.`channelId` = '{$channelId}'";
                $sqlSon .=" AND b.`channelId` = '{$channelId}'";
            }
            if(!empty($mobile))
            {
                //echo '2.....';
                $sql .=" AND b.`mobile` = '{$mobile}'";
                $sqlIsparent .=" AND b.`mobile` = '{$mobile}'";
                $sqlSon .=" AND b.`mobile` = '{$mobile}'";
            }
            if(!empty($nickname))
            {
                //echo '3.....';
                $sql .=" AND b.`nickname` = '{$nickname}'";
                $sqlIsparent .=" AND b.`nickname` = '{$nickname}'";
                $sqlSon .=" AND b.`nickname` = '{$nickname}'";
            }
            if(!empty($goodsid))
            {
                //echo '4.....';
                // $sqlIsparent不能连接ims_ewei_shop_order_goods表，否则为空
                $sql .=" AND c.`goodsid` = {$goodsid}";
                $sqlSon .=" AND c.`goodsid` = {$goodsid}";
            }
            if(!empty($shippingType))
            {
                if($shippingType==1)
                {
                    //echo '51.....';
                    $sql .=" AND a.`status` < 3";
                    $sqlIsparent .=" AND a.`status` < 3";
                    $sqlSon .=" AND a.`status` < 3";
                }
                else{
                    //echo '52.....';
                    $sql .=" AND a.`status` = 3";
                    $sqlIsparent .=" AND a.`status` = 3";
                    $sqlSon .=" AND a.`status` = 3";
                }
            }
            $sql .= ' ORDER BY a.`id`, b.`id`, b.`comefrom`, b.`channelId`';
            $sqlSon .=" AND a.`parentid` in ";
            $category_list = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                ->query($sql);
//            echo $sql . '<br/>';
//            echo $sqlIsparent . '<br/>';
//            echo $sqlSon . '<br/>';
//            return;

            // 组合数据
            $data = [
                'mId' => -1,
                'realName' => "",
                'mobile' => "",
                'nickName' => "",
                'orderId' => -1,
                'orderSn' => "",
                'totalPrice' => -1.0,
                'goodsPrice' => -1.0,
                'discountPrice' => -1.0,
                'dispatchPrice' => -1.0,
                'parentId' => -1,
                'status' => -1,
                'goodsInfo' => [],
                'createTime' => -1
            ];
            $goodsInfo = [
                'goodsId' => -1,
                'goodsName' => "",
                'price' => -1.0,
                'total' => -1.0
            ];

            $dataArray = [];
            $goodsInfoArray = array();
            $comefromVar = '';
            $channelIdVar = '';
            foreach ($category_list as $item) {
                // 如果mid与orderid相同，就要合并到goodsinfo里
                if( $data['mId'] == $item['mid'] && $data['orderId'] == $item['orderid'] &&
                    $comefromVar == $item['comefrom'] && $channelIdVar == $item['channelId'] )
                {
                    $goodsInfo = [
                        'goodsId' => -1,
                        'goodsName' => "",
                        'price' => -1.0,
                        'total' => -1.0
                    ];

                    // 嵌套的json begin
                    $goodsInfo['goodsId'] = $item['goodsid'];
                    $goodsInfo['goodsName'] = $item['title'];
                    $goodsInfo['price'] = $item['price'];
                    $goodsInfo['total'] = $item['total'];
                    $goodsInfoArray[] = $goodsInfo;
                }
                else
                {
                    if(count($goodsInfoArray)>0)
                    {
                        // 先存储前面保存的
                        $data['goodsInfo'] = $goodsInfoArray;
                        $dataArray[] = $data;
                    }
                    // 初始化
                    $goodsInfoArray = array(); // 清空
                    $data = [
                        'mId' => -1,
                        'realName' => "",
                        'mobile' => "",
                        'nickName' => "",
                        'orderId' => -1,
                        'orderSn' => "",
                        'totalPrice' => -1.0,
                        'goodsPrice' => -1.0,
                        'discountPrice' => -1.0,
                        'dispatchPrice' => -1.0,
                        'parentId' => -1,
                        'status' => -1,
                        'goodsInfo' => [],
                        'createTime' => -1
                    ];
                    $goodsInfo = [
                        'goodsId' => -1,
                        'goodsName' => "",
                        'price' => -1.0,
                        'total' => -1.0
                    ];
                    $comefromVar = '';
                    $channelIdVar = '';

                    $data['mId'] = $item['mid'];
                    $data['realName'] = $item['realname'];
                    $data['mobile'] = $item['mobile'];
                    $data['nickName'] = $item['nickname'];
                    $data['orderId'] = $item['orderid'];
                    $data['orderSn'] = $item['ordersn'];
                    $data['totalPrice'] = $item['totalprice'];
                    $data['goodsPrice'] = $item['goodsprice'];
                    $data['discountPrice'] = $item['discountprice'];
                    $data['dispatchPrice'] = $item['dispatchprice'];
                    $data['parentId'] = $item['parentid'];
                    $data['status'] = $item['status'];
                    $comefromVar = $item['comefrom'];
                    $channelIdVar = $item['channelId'];
                    // 嵌套的json begin
                    $goodsInfo['goodsId'] = $item['goodsid'];
                    $goodsInfo['goodsName'] = $item['title'];
                    $goodsInfo['price'] = $item['price'];
                    $goodsInfo['total'] = $item['total'];
                    $goodsInfoArray[] = $goodsInfo;
                    // 嵌套的json end
                    $data['createTime'] = date("Y-m-d H:i:s",$item['createtime']);

                    //$goodsInfoArray = array(); // 清空
                }
            }
            if(count($goodsInfoArray)>0)
            {
                // 先存储前面保存的
                $data['goodsInfo'] = $goodsInfoArray;
                $dataArray[] = $data;
                $goodsInfoArray = array();  //清空
            }

            // 处理isparent=1的记录
            // 排序
            $sqlIsparent .= ' ORDER BY a.`id`, b.`id`, b.`comefrom`, b.`channelId`';
            $category_list_outer = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                ->query($sqlIsparent);
            $sqlSonNew = $sqlSon;
            foreach ($category_list_outer as $item_outer) {
                // 初始化
                $data = [
                    'mId' => -1,
                    'realName' => "",
                    'mobile' => "",
                    'nickName' => "",
                    'orderId' => -1,
                    'orderSn' => "",
                    'totalPrice' => -1.0,
                    'goodsPrice' => -1.0,
                    'discountPrice' => -1.0,
                    'dispatchPrice' => -1.0,
                    'parentId' => -1,
                    'status' => -1,
                    'goodsInfo' => [],
                    'createTime' => -1
                ];
                $goodsInfo = [
                    'goodsId' => -1,
                    'goodsName' => "",
                    'price' => -1.0,
                    'total' => -1.0
                ];
                $comefromVar = '';
                $channelIdVar = '';

                // 再查询parentid = orderid记录
                $sqlSonNew = $sqlSon . "(" . $item_outer['orderid'] .")";
                //////////////////////
                // 先添加父记录
                $data['mId'] = $item_outer['mid'];
                $data['realName'] = $item_outer['realname'];
                $data['mobile'] = $item_outer['mobile'];
                $data['nickName'] = $item_outer['nickname'];
                $data['orderId'] = $item_outer['orderid'];
                $data['orderSn'] = $item_outer['ordersn'];
                $data['totalPrice'] = $item_outer['totalprice'];
                $data['goodsPrice'] = $item_outer['goodsPrice'];
                $data['discountPrice'] = $item_outer['discountprice'];
                $data['dispatchPrice'] = $item_outer['dispatchprice'];
                $data['parentId'] = $item_outer['parentid'];
                $data['status'] = $item_outer['status'];
                $data['goodsInfo'] = $goodsInfo;    // 父目录的goodsInfo是空的
                $data['createTime'] = $item_outer['createtime'];
                $comefromVar = $item_outer['comefrom'];
                $channelIdVar = $item_outer['channelId'];
                $dataArray[] = $data;
                //////////////////////
                // 排序
                $sqlSonNew .= ' ORDER BY a.`id`, b.`id`, b.`comefrom`, b.`channelId`';
                $category_list_inner = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                    ->query($sqlSonNew);

                $goodsInfoArray = array();
                foreach ($category_list_inner as $item_inner) {
                    // 如果mid与orderid相同，就要合并到goodsinfo里
                    if( $data['mId'] == $item_inner['mid'] && $data['orderId'] == $item_inner['orderid'] &&
                        $comefromVar == $item_inner['comefrom'] && $channelIdVar == $item_inner['channelId'])
                    {
                        $goodsInfo = [
                            'goodsId' => -1,
                            'goodsName' => "",
                            'price' => -1.0,
                            'total' => -1.0
                        ];

                        // 嵌套的json begin
                        $goodsInfo['goodsId'] = $item_inner['goodsid'];
                        $goodsInfo['goodsName'] = $item_inner['title'];
                        $goodsInfo['price'] = $item_inner['price'];
                        $goodsInfo['total'] = $item_inner['total'];
                        $goodsInfoArray[] = $goodsInfo;
                    }
                    else
                    {
                        if(count($goodsInfoArray)>0)
                        {
                            // 先存储前面保存的
                            $data['goodsInfo'] = $goodsInfoArray;
                            $dataArray[] = $data;
                        }

                        // 第一次不同的ID
                        $goodsInfoArray = array(); // 清空
                        // 初始化
                        $data = [
                            'mId' => -1,
                            'realName' => "",
                            'mobile' => "",
                            'nickName' => "",
                            'orderId' => -1,
                            'orderSn' => "",
                            'totalPrice' => -1.0,
                            'goodsPrice' => -1.0,
                            'discountPrice' => -1.0,
                            'dispatchPrice' => -1.0,
                            'parentId' => -1,
                            'status' => -1,
                            'goodsInfo' => [],
                            'createTime' => -1
                        ];
                        $goodsInfo = [
                            'goodsId' => -1,
                            'goodsName' => "",
                            'price' => -1.0,
                            'total' => -1.0
                        ];
                        $comefromVar = '';
                        $channelIdVar = '';

                        $data['mId'] = $item_inner['mid'];
                        $data['realName'] = $item_inner['realname'];
                        $data['mobile'] = $item_inner['mobile'];
                        $data['nickName'] = $item_inner['nickname'];
                        $data['orderId'] = $item_inner['orderid'];
                        $data['orderSn'] = $item_inner['ordersn'];
                        $data['totalPrice'] = $item_inner['totalprice'];
                        $data['goodsPrice'] = $item_inner['goodsPrice'];
                        $data['discountPrice'] = $item_inner['discountprice'];
                        $data['dispatchPrice'] = $item_inner['dispatchprice'];
                        $data['parentId'] = $item_inner['parentid'];
                        $data['status'] = $item_inner['status'];
                        $comefromVar = $item_inner['comefrom'];
                        $channelIdVar = $item_inner['channelId'];
                        // 嵌套的json begin
                        $goodsInfo['goodsId'] = $item_inner['goodsid'];
                        $goodsInfo['goodsName'] = $item_inner['title'];
                        $goodsInfo['price'] = $item_inner['price'];
                        $goodsInfo['total'] = $item_inner['total'];
                        $goodsInfoArray[] = $goodsInfo;
                        // 嵌套的json end
                        $data['createTime'] = date("Y-m-d H:i:s",$item_inner['createtime']);
                    }
                }
            }
            if(count($goodsInfoArray)>0)
            {
                // 先存储前面保存的
                $data['goodsInfo'] = $goodsInfoArray;
                $dataArray[] = $data;
            }

            $this->success('success', $dataArray, 0);
        } else if ($method == 'POST') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'PUT') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'DELETE') {
            $this->error('請求方式錯誤',null,-99);
        }

        $this->error('請求方式錯誤',null,-99);
    }

    /*
     * 提供查詢美果商城訂單詳情，主訂單isparent=1不提供查詢
     * 請求：GET http://mg.acciot.com.tw/api/river/Getorderdetail?orderid=0&token=xxx
     * 說明：提供查詢美果商城訂單詳情，主訂單isparent=1不提供查詢
        json格式如下：
            {mid,realname,mobile,nickname,orderid,goodsid,title,price,total,agentid,ismerch,ordersn,price,
    goodsprice,discountprice,status,createtime,finishtime,paytime,sendtime,address }

        mid, 會員ID
        realname, 真實姓名
        mobile, 手機號碼
        nickname, Line 暱稱
        orderid: 訂單ID
        goodsid, 商品ID
        title: 商品名稱
        price, 售價
        total, 數量
        agentid, 分銷商ID
        ismerch, 0: 主訂單  數字: 商戶ID
        ordersn, 訂單編號
        price, 訂單總金額
        goodsprice, 商品金額
        discountprice, 折扣金額
        status, 0: 待付款 1: 待出貨(待使用) 2:待收貨 3:已完成  -1:已關閉
        createtime, 訂單成立時間
        finishtime, 訂單完成時間
        paytime, 付款時間
        sendtime, 發貨時間
        address, 收貨信息
    */
    // GET http://mg.acciot.com.tw/api/river/getOrderDetail?orderId=331&token=xxx
    // GET http://localhost:9100/api/river/getOrderDetail?orderId=331&token=ba208acc7a34fe1b88b8796cf1e55203
    public function getOrderDetail()
    {
        // 判断token正确否？
        $token = $this->request->request('token');
        if(!$token)
        {
            $this->error("error token", null, -2);
        }
        $ret = self::isTokenExperiod($token);
        if($ret == -1)  // 不存在，token值错误
        {
            $this->error("error token", null, -2);
        }
        else if($ret == -2) // token过期
        {
            $this->error("token is experiod", null, -19);
        }
        $method = $this->request->method();
        if ($method == 'GET') {
            $orderid = $this->request->request('orderId');
            if(!$orderid)
            {
                $this->error("orderid cannot be NULL", null, -21);
            }
            else
            {
                $sql = "SELECT b.`id` as mid, b.`realname`, b.`mobile`, b.`nickname`,";
                $sql .=" c.`goodsid`, c.`price`, c.`total`,";
                $sql .=" a.`id` as orderid, a.`ordersn`, a.`price` as totalprice, a.`goodsprice`, a.`discountprice`, a.`dispatchprice`, a.`agentid`, a.`merchid`,";
                $sql .=" a.`status`, a.`createtime`, a.`finishtime`, a.`paytime`, a.`sendtime`, a.`address`, d.`title`, d.`thumb`";
                $sql .=" FROM ims_ewei_shop_order a INNER JOIN ims_ewei_shop_member b ON a.`openid` = b.`openid`";
                $sql .=" INNER JOIN ims_ewei_shop_order_goods c ON  a.`id` = c.`orderid`";
                $sql .=" INNER JOIN ims_ewei_shop_goods d ON c.`goodsid` = d.`id`";
                $sql .=" WHERE a.`id` = {$orderid} AND a.`isparent` != 1";
                $sql .=" AND a.`status` >= 0";
            }
            $sql .= ' ORDER BY a.`id`, b.`id`';
            $category_list = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                ->query($sql);
            // 初始化
            $data = [
                'mId' => -1,
                'realName' => "",
                'mobile' => "",
                'nickName' => "",
                'orderId' => -1,
                'agentId' => -1,
                'merchId' => -1,
                'orderSn' => "",
                'totalPrice' => -1.0,
                'goodsPrice' => -1.0,
                'discountPrice' => -1.0,
                'dispatchPrice' => -1.0,
                'status' => -1,
                'createTime' => -1,
                'finishTime' => -1,
                'payTime' => -1,
                'sendTime' => -1,
                'address' => '',
                'goodsInfo' => []
            ];
            $goodsInfo = [
                'goodsId' => -1,
                'goodsName' => "",
                'price' => -1.0,
                'total' => -1.0,
                'thumb' => ""
            ];

            // 组合数据
            $dataArray = [];
            $goodsInfoArray = array();
            foreach ($category_list as $item) {
                // 如果mid与orderid相同，就要合并到goodsinfo里
                if($data['mId'] == $item['mid'] && $data['orderId'] == $item['orderid'])
                {
                    // 理论上不应该有
                    $goodsInfo = [
                        'goodsId' => -1,
                        'goodsName' => "",
                        'price' => -1.0,
                        'total' => -1.0,
                        'thumb' => ""
                    ];

                    // 嵌套的json begin
                    $goodsInfo['goodsId'] = $item['goodsid'];
                    $goodsInfo['goodsName'] = $item['title'];
                    $goodsInfo['price'] = $item['price'];
                    $goodsInfo['total'] = $item['total'];
                    $thumb = $item['thumb'];
                    if(substr($thumb,0,5) != "http:")
                    {
                        $thumb = 'https://image.localmuzi.com/' . $thumb;
                    }
                    $goodsInfo['thumb'] = $thumb;
                    $goodsInfoArray[] = $goodsInfo;
                }
                else
                {
                    if(count($goodsInfoArray)>0)
                    {
                        // 先存储前面保存的
                        $data['goodsInfo'] = $goodsInfoArray;
                        $dataArray[] = $data;
                    }

                    // 第一次不同的ID
                    $goodsInfoArray = array();
                    // 初始化
                    $data = [
                        'mId' => -1,
                        'realName' => "",
                        'mobile' => "",
                        'nickName' => "",
                        'orderId' => -1,
                        'agentId' => -1,
                        'merchId' => -1,
                        'orderSn' => "",
                        'totalPrice' => -1.0,
                        'goodsPrice' => -1.0,
                        'discountPrice' => -1.0,
                        'dispatchPrice' => -1.0,
                        'status' => -1,
                        'createTime' => -1,
                        'finishTime' => -1,
                        'payTime' => -1,
                        'sendTime' => -1,
                        'address' => '',
                        'goodsInfo' => []
                    ];
                    $goodsInfo = [
                        'goodsId' => -1,
                        'goodsName' => "",
                        'price' => -1.0,
                        'total' => -1.0,
                        'thumb' => ""
                    ];

                    $data['mId'] = $item['mid'];
                    $data['realName'] = $item['realname'];
                    $data['mobile'] = $item['mobile'];
                    $data['nickName'] = $item['nickname'];
                    $data['orderId'] = $item['orderid'];
                    $data['agentId'] = $item['agentid'];
                    $data['merchId'] = $item['merchid'];
                    $data['orderSn'] = $item['ordersn'];
                    $data['totalPrice'] = $item['totalprice'];
                    $data['goodsPrice'] = $item['goodsprice'];
                    $data['discountPrice'] = $item['discountprice'];
                    $data['dispatchPrice'] = $item['dispatchprice'];
                    $data['status'] = $item['status'];
                    $data['createTime'] = date("Y-m-d H:i:s",$item['createtime']);
                    $data['finishTime'] = date("Y-m-d H:i:s",$item['finishtime']);
                    $data['payTime'] = date("Y-m-d H:i:s",$item['paytime']);
                    $data['sendTime'] = date("Y-m-d H:i:s",$item['sendtime']);
                    $data['address'] = $item['address'];
                    // 嵌套的json begin
                    $goodsInfo['goodsId'] = $item['goodsid'];
                    $goodsInfo['goodsName'] = $item['title'];
                    $goodsInfo['price'] = $item['price'];
                    $goodsInfo['total'] = $item['total'];
                    $thumb = $item['thumb'];
                    if(substr($thumb,0,5) != "http:")
                    {
                        $thumb = 'https://image.localmuzi.com/' . $thumb;
                    }
                    $goodsInfo['thumb'] = $thumb;
                    $goodsInfoArray[] = $goodsInfo;
                    //$data['goodsInfo'] = $goodsInfoArray;
                    // 嵌套的json end
                    //$dataArray[] = $data;
                }
            }
            // 先存储前面保存的
            if(count($goodsInfoArray)>0)
            {
                // 先存储前面保存的
                $data['goodsInfo'] = $goodsInfoArray;
                $dataArray[] = $data;

                // 清空
                $data = [
                    'mId' => -1,
                    'realName' => "",
                    'mobile' => "",
                    'nickName' => "",
                    'orderId' => -1,
                    'agentId' => -1,
                    'merchId' => -1,
                    'orderSn' => "",
                    'totalPrice' => -1.0,
                    'goodsPrice' => -1.0,
                    'discountPrice' => -1.0,
                    'dispatchPrice' => -1.0,
                    'status' => -1,
                    'createTime' => -1,
                    'finishTime' => -1,
                    'payTime' => -1,
                    'sendTime' => -1,
                    'address' => '',
                    'goodsInfo' => []
                ];
                $goodsInfo = [
                    'goodsId' => -1,
                    'goodsName' => "",
                    'price' => -1.0,
                    'total' => -1.0,
                    'thumb' => ""
                ];
                $goodsInfoArray = array();
            }

            if(!empty($dataArray))
            {
                // 插入fa_river_json数据库
                $jsonstring = json_encode($dataArray);
                $md5 = md5($jsonstring);
                $jsonInfo = \app\admin\model\river\Json::where('md5', $md5)->find();
                if (!$jsonInfo) {
                    $json = new \app\admin\model\river\Json();
                    $json->json = $jsonstring;
                    $json->md5 = $md5;
                    $json->save();
                    $id = $json->id;
                }
                else{
                    $id = $jsonInfo['id'];
                }
                $url = "http://" . $_SERVER['HTTP_HOST'] . "/index/river?id=" . $id;
                $data = array(
                    "url" => $url,
                    "json" => $dataArray
                );

                $this->success('success', $data, 0);
            }
            else
            {
                $this->success('no found!', '', 0);
            }
        } else if ($method == 'POST') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'PUT') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'DELETE') {
            $this->error('請求方式錯誤',null,-99);
        }

        $this->error('請求方式錯誤',null,-99);
    }

    /*
     * 提供查詢美果商城訂單詳情，主訂單isparent=1不提供查詢
     * 請求：GET http://mg.acciot.com.tw/api/river/Getorderdetail?orderid=0&token=xxx
     * 說明：提供查詢美果商城訂單詳情，主訂單isparent=1不提供查詢
     *   參數名稱	    說明	    格式	長度	必要	備註
     *   nickName	    會員昵稱	    String	255	    Y
     *   platformType	平臺類型	    String	20	    N	FB, LINE, WEIXIN
     *   userID	        用戶ID	    String	50	    Y
     *   pictureURL	    用戶頭像URL	String	255	    N	沒有就用默認頭像
     *   isAgent	    是否分銷商	Integer	1	    N	是否分銷商：如果不輸入，默認為0
     *                                                  1代表是分銷商
     *                                                  0代表不是分銷商
     *   token	        訪問命令串	String	32	    Y
    */
    // POST http://mg.acciot.com.tw/api/river/SetUserInfo?nickname=xxx&userID=xxx&pictureURL=xxx&token=xxx
    // POST http://localhost:9100/api/river/SetUserInfo?nickname=xxx&userID=xxx&pictureURL=xxx&token=xxx
    public function setUserInfo()
    {
//        $data = $_POST;   // type:array
//        $data['success'] = $data;     // type:array
//        $encodedata = json_encode($data); // type:string
        $data = file_get_contents("php://input");   // type: string
        $decodedata = json_decode($data,true);  // type: array
        header('content-type:application/json');
        // 判断token正确否？
        if(!array_key_exists("token", $decodedata))
        {
            $this->error("error token", null, -2);
        }
        $ret = self::isTokenExperiod($decodedata['token']);

        if($ret == -1)  // 不存在，token值错误
        {
            $this->error("error token", null, -2);
        }
        else if($ret == -2) // token过期
        {
            $this->error("token is experiod", null, -19);
        }

        $method = $this->request->method();
        if ($method == 'GET') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'POST') {
            if(!array_key_exists("nickName", $decodedata))
            {
                $this->error("nickname cannot be NULL", null, -98);
            }
            $nickname = $decodedata['nickName'];

            if(array_key_exists("platformType", $decodedata))
            {
                $platformType = strtoupper($decodedata['platformType']);
            }

            if(array_key_exists("channelId", $decodedata))
            {
                $channelid = strtoupper($decodedata['channelId']);
            }

            if(!array_key_exists("platformId", $decodedata))
            {
                $this->error("userID cannot be NULL", null, -98);
            }
            else
            {
                $lineId = $decodedata['platformId'];
            }

            if(!array_key_exists("pictureURL", $decodedata))
            {
                $pictureURL = '';
            }
            else
            {
                $pictureURL = $decodedata['pictureURL'];
            }

            if(!array_key_exists("isAgent", $decodedata))
            {
                $isAgent = 0;
            }
            else{
                $isAgent = strtoupper($decodedata['isAgent']);
                if($isAgent == 'Y')
                    $isAgent = 1;
                else
                    $isAgent = 0;
            }

            if($channelid)
            {
                // 要串接openid=yyyyyyyyy-xxxxx
                //xxxxx為channelID
                //yyyyy為paltfromID
                $openid = $lineId . '-' . $channelid;
            }
            else if($platformType && $platformType == "LINE")
                $openid = 'LINE_' . $lineId;
            else
                $openid = $lineId;

            // 查询看ims_ewei_shop_member表里，是不是已经存在？
            $sql = "SELECT id,nickname,line_userid,avatar FROM ims_ewei_shop_member";
            $sql .= " WHERE upper(comefrom) = '{$platformType}' AND openid= '{$openid}' AND upper(channelId) = '{$channelid}'";
            $category_list = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                ->query($sql);

            if(!empty($category_list))
            {
                // 已经存在
                $this->success('success', "Exsit!", 0);
            }

            $pwd = md5('123456aitrip2016');
            $createtime = time();
            $agenttime = time();

            // 要添加isagent和agenttime
            $sql = "INSERT INTO ims_ewei_shop_member(uniacid,avatar,nickname,realname,openid,line_userid,pwd,salt,createtime,comefrom,agenttime,isagent,channelId)";
            $sql .= " VALUES(2,'{$pictureURL}','{$nickname}','{$nickname}','{$openid}','{$lineId}','{$pwd}','2016',{$createtime},'{$platformType}',{$agenttime},{$isAgent},'{$channelid}')";
            $result = Db::connect('mysql://megoshop:Aitrip123@52.198.57.105:3306/megoshop#utf8')
                ->query($sql);

            $this->success('success', "Insert ok!", 0);
        } else if ($method == 'PUT') {
            $this->error('請求方式錯誤',null,-99);
        } else if ($method == 'DELETE') {
            $this->error('請求方式錯誤',null,-99);
        }

        $this->error('請求方式錯誤',null,-99);
    }

    /*
    * 写入fa_river_tokenbackup数据库表
    */
    public function writeTokenBackup($MakeTokenRowMaterial, $tokenNew)
    {
        $item = new \app\admin\model\river\Tokenbackup();

        $item->tokenBefore = $MakeTokenRowMaterial;
        $item->token = $tokenNew;
        $item->create_time = time();

        $item->save();
    }
}